import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/entity/native_entity.dart';
import 'package:panda/goods_by_cat_list/SearchGoods.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';

class CatePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CateFragmentState();
  }
}

class CateFragmentState extends State<CatePage> with WidgetsBindingObserver {
  List<NativeData> _datas = List(); //一级分类集合
  List<NativeDataArticle> articles = List(); //二级分类集合
  int index; //一级分类下标
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      if (!ModalRoute.of(context).isCurrent) {
        return;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: PreferredSize(
          child: AppBar(
            brightness: Brightness.dark,
            backgroundColor: mainColor,
            elevation: 0,
          ),
          preferredSize: Size.fromHeight(0)),
      body: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_15)),
            color: mainColor,
            child: Center(
              child: new Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: new GestureDetector(
                      child: Container(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(DP_20),
                            ScreenUtil.getInstance().setWidth(DP_10),
                            ScreenUtil.getInstance().setHeight(DP_20),
                            ScreenUtil.getInstance().setWidth(DP_10)),
                        margin: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(DP_30),
                            0,
                            ScreenUtil.getInstance().setHeight(DP_30),
                            0),
                        decoration: BoxDecoration(
                            color: Color.fromARGB(255, 255, 255, 255),
                            borderRadius: BorderRadius.circular(8.0)),
                        child: new Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.search,
                              size: ScreenUtil.getInstance().setWidth(DP_50),
                              color: Colors.black26,
                            ),
                            Text(
                              '搜索商品、品牌',
                              style: TextStyle(
                                  color: Colors.black54,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE + 4)),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                         Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new SearchGoodsListPage();
                            }));
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Expanded(
                  flex: 2,
                  child: Container(
                    color: divideColor,
                    child: ListView.builder(
                      itemCount: _datas.length,
                      itemBuilder: (BuildContext context, int position) {
                        return getRow(position);
                      },
                    ),
                  ),
                ),
                // Expanded(
                //     flex: 5,
                //     child: Container(
                //       //height: double.infinity,
                //       alignment: Alignment.topLeft,
                //       padding: const EdgeInsets.all(10),
                //       color: Colors.white,
                //       child: getChip(index), //传入一级分类下标
                //     )),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget getRow(int i) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(bottom: 1),
        color: Colors.white,
        //Container下的color属性会与decoration下的border属性冲突，所以要用decoration下的color属性
        child: Row(
          children: <Widget>[
            _datas[i].icon == null || _datas[i].icon == ''
                ? Center()
                : ClipOval(
                    child: CachedNetworkImage(
                      imageUrl: Api.ImgBaseUrl + _datas[i].icon,
                      width: 50,
                      fit: BoxFit.cover,
                      height: 50,
                    ),
                  ),
            Text(
              _datas[i].name,
              style: TextStyle(
                color:  Colors.black54,
                fontWeight: FontWeight.w400,
                fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE + 10),
              ),
            )
          ],
        ),
      ),
      onTap: () {
        setState(() {
          index = i; //记录选中的下标
        });
      },
    );
  }

//   Widget getChip(int i) {
//     //更新对应下标数据
//     _updateArticles(i);
//     return GridView.builder(
//         itemCount: articles.length,
//         //SliverGridDelegateWithFixedCrossAxisCount 构建一个横轴固定数量Widget
//         gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//             //横轴元素个数
//             crossAxisCount: 3,
//             //纵轴间距
// //            //横轴间距
// //            crossAxisSpacing: 10.0,
//             childAspectRatio: 0.8),
//         itemBuilder: (BuildContext context, int index) {
//           //Widget Function(BuildContext context, int index)
//           return getItemContainer(articles[index]);
//         });
//   }

  Widget getItemContainer(NativeDataArticle item) {
    return new SingleChildScrollView(
      child: new GestureDetector(
        onTap: () {
          // Navigator.of(context).push(new MaterialPageRoute(builder:(context){
          //     return new ServiceListByCatPage(cat_id: item.cat_id,cat_name: item.name,type:2);
          // }));
        },
        child: new ConstrainedBox(
            constraints: new BoxConstraints(minHeight: 1),
            child: Column(
              children: <Widget>[
                Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    child: new ClipOval(
                        child: CachedNetworkImage(
                      imageUrl: Api.BaseUrl + item.icon,
                      width: ScreenUtil.getInstance().setWidth(DP_100),
                      height: ScreenUtil.getInstance().setWidth(DP_100),
                      fit: BoxFit.fill,
                    ))),
                Text(
                  item.name,
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            )),
      ),
    );
  }

  /// 根据一级分类下标更新二级分类集合
  List<NativeDataArticle> _updateArticles(int i) {
    setState(() {
      if (_datas.length != 0) articles = _datas[i].articles;
    });
    return articles;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    getHttp();
  }

  void getHttp() async {
    try {
      var response =
          await HttpUtil().post(Api.BaseUrl + "/index.php/wap/Brand/getList");
      Map userMap = json.decode(response.toString());
      var naviEntity = NativeEntity.fromJson(userMap);
      setState(() {
        _datas = naviEntity.data;
        index = 0;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this); //销毁观察者
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
